<template>
  <div>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-row :gutter="10">
            <el-col :span="2">
              <el-select v-model="searchForm.roleId" style="width: 100%" size="large">
                <el-option label="全部角色" :value="''" />
                <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-input v-model="searchForm.key" size="large" clearable placeholder="模糊匹配姓名和手机"></el-input>
            </el-col>
            <el-col :span="2">
              <el-button @click="doSearch()" size="large">搜素</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <el-table :data="data.page.records" style="width: 100%">
        <el-table-column label="#" width="70" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="" width="40" align="center">
          <template #default="scope">
            <el-avatar size="small" :src="scope.row.userImg" />
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="姓名" />
        <el-table-column prop="userTel" label="手机号码"  align="center"/>
        <el-table-column label="角色" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.roleId" class="m-2" @change="doUpdateRole(scope.row)">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="锁定状态" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.userLocked" @change="doUpdateLock(scope.row)" />
          </template>

        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button size="small" type="warning"
                @click="pwd.open = true; pwd.form.userId = scope.row.userId; pwd.form.userPwd = '';">
                重置密码
              </el-button>
              <el-button size="small" type="danger" @click="doDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>


    </el-card>

    <el-pagination style="justify-content: center;" v-model:currentPage="data.params.current"
      v-model:page-size="data.params.size" :page-sizes="[10, 20, 50]" background
      layout="total, sizes, prev, pager, next, jumper" :total="Number(data.page.total)" @size-change="doPage(1);"
      @current-change="doPage();" />




    <!-- 重置密码对话框 -->
    <el-dialog v-model="pwd.open" title="修改对话框" width="30rem" draggable>
      <el-form ref="pwdForm" :model="pwd.form" label-width="8em" label-position="right" size="large" status-icon>
        <el-form-item label="新密码" prop="userPwd" :rules="[
          { required: true, message: '密码必填' },
          {
            pattern: /^.{2,10}$/,
            message: '密码必须为2-10个字符组成',
          },
        ]">
          <el-input v-model="pwd.form.userPwd" type="password" clearable show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="doPwd()">重置密码</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>




<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";

import userApi from "@/api/sys/UserApi";
import roleApi from "@/api/sys/RoleApi";

// const roleList = reactive({});
const data = reactive({
  params: {
    current: 1,//当前页码
    size: 10,//每页最大数
  },
  page: {//分页结果
    total: 0,//总记录数
    records: [],//记录
  }
}); //定义复制的响应式数据

//带条件的分页查询
const roleList = ref([]);
const searchForm = ref({ roleId: '', key: '' });
const doSearch = () => {
  data.params={...data.params,...searchForm.value};//
  doPage(1);
}

/**
 * 加载第p页数据
 * @param {Number} p 
 */
const doPage = (p) => {
  if (p) {
    data.params.current = p
  }
  userApi.page(data.params).then(r => {
    data.page = r.data.data;
  });
}


/**
 * 组件挂载事件
 */
onMounted(() => {
  doPage(1);
  roleApi.list().then(r => {
    roleList.value = r.data.data;
  });
});



// 删除处理
const doDelete = (row) => {
  ElMessageBox.confirm(`您确定要删除[${row.userName}]吗?`, "删除确认")
    .then(() => {
      return userApi.delete(row.userId);
    })
    .then((r) => {
      if (r.data.ok) {
        ElMessage.success("删除成功"); //1.成功提示
        doPage(1); //2.调用加载数据的方法,刷新页面数据
      }
    });
};

//修改用户角色
const doUpdateRole = (row) => {
  userApi.update({userId:row.userId,roleId:row.roleId}).then(r=>{
    if (r.data.ok) {
        ElMessage.success("设置角色成功"); 
      }
  })
}

//修改用户锁定状态
const doUpdateLock = (row) => {
  userApi.update({ userId: row.userId, userLocked: row.userLocked }).then(r => {
    if (r.data.ok) {
      ElMessage.success((row.userLocked ? "锁定" : "解锁") + "用户成功");
    }
  });
}


//重置密码
const pwd = reactive({
  open: false,
  form: {
    userId: 0,
    userPwd: ""
  }
});
const pwdForm = ref(null);
const doPwd = () => {
  pwdForm.value.validate((valid) => {
    if (valid) {
      //校验成功
      userApi.resetPwd(pwd.form).then(r => {
        if (r.data.ok) {
          ElMessage.success("重置用户密码成功");
          pwd.open = false;
        }
      });
    } else {
      ElMessage.error("校验失败");
    }
  });

}
</script>

<style  scoped>
.box-card {
  width: 96%;
  margin: 1rem auto;
}
</style>